#include "HelloWorldScene.h"

USING_NS_CC;
USING_NS_CC_EXT;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
	setTouchEnabled( true );

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

 //   /////////////////////////////
 //   // 2. add a menu item with "X" image, which is clicked to quit the program
 //   //    you may modify it.

 //   // add a "close" icon to exit the progress. it's an autorelease object
 //   CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
 //                                       "CloseNormal.png",
 //                                       "CloseSelected.png",
 //                                       this,
 //                                       menu_selector(HelloWorld::menuCloseCallback));
 //   
	//pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
 //                               origin.y + pCloseItem->getContentSize().height/2));

 //   // create menu, it's an autorelease object
 //   CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
 //   pMenu->setPosition(CCPointZero);
 //   this->addChild(pMenu, 1);


    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("skype_1024.png");

    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);


	 // create a void node, a parent node
    //CCParallaxNode* voidNode = CCParallaxNode::create();

    // NOW add the 3 layers to the 'void' node
    
	



	//CCActionInterval* goUp = CCMoveBy::create(1.5f, ccp(1000,0) );
 //   CCActionInterval* goDown = goUp->reverse();

	//CCSequence* seq = CCSequence::create(goUp, goDown, NULL);
 //   _backgroundNode->runAction( (CCRepeatForever::create(seq) ));

	visibleSize = CCDirector::sharedDirector()->getVisibleSize();

	monkeyNode = CCNode::create();
	m_Monkey = Monkey::create(monkeyNode);
	m_Monkey->setZOrder(4);
	m_Monkey->setStatus(MKCLIMBING);
	this->addChild(m_Monkey);


	//player->setPositionX(visibleSize.width/2);



	m_PList = ParallaxList::create(m_Monkey);
	m_CurrentTree = m_PList->fGetCurrentTree();
	this->addChild(m_PList,2);

	//fAddMonkey();

	isTouchDown = false;
    
    initialTouchPos[0] = 0;
    initialTouchPos[1] = 0;

	this->scheduleUpdate();

    return true;
}

// Background scroll here
void  HelloWorld::update(float delta){

	// update Cloud
	//CCObject *obj;
	//CCARRAY_FOREACH(this->clouds, obj)
	//{
	//	Cloud *singleCloud = (Cloud *)obj;
 //       singleCloud->setPositionX(singleCloud->getPositionX() - 2);
 //       if(singleCloud->getPositionY() > visibleSize.height) {
 //           singleCloud->setTag(TREE_NEW);
 //       }
 //   }


	if (true == isTouchDown)
    {
		// Check swipe and move to
		CCObject *obj;

		int i = 0;
		CCARRAY_FOREACH(m_PList->fGetTrees(), obj){
			Tree *singleTree = (Tree *)obj;
			if (singleTree->fGetIsChoose() == true) 
			{
				//CCLog("Tim thay cay duoc chon");
				// Tim cay ben trai va ben phai cua cay hien tai
				m_CurrentTree = i;
				m_leftTree = i-1;
				m_RightTree = i+1;
			}
			i++;
		}
		// do something when swipe is detected

        if (initialTouchPos[0] - currentTouchPos[0] > visibleSize.width * 0.05)
        {
            CCLOG("SWIPED LEFT");

			if(m_leftTree >= 0)
			{
				// m_PList->fParallaxMoveTo(ccp(500 + visibleSize.width/2 - m_PList->fGetSizeX() - atree->fGetLeftX() + 200 ,visibleSize.height/2));
				Tree *t = (Tree *) m_PList->fGetTrees()->objectAtIndex(m_leftTree);

				// Remove isChoose o cay hien tai
				Tree *t2 = (Tree *) m_PList->fGetTrees()->objectAtIndex(m_CurrentTree);
				t2->fSetIsChoose(false);

				t->fSetIsChoose(true);
				float moveToX = t->fGetRightX();
				CCLog("Move to X = %f",moveToX);
				m_PList->fParallaxMoveTo(ccp(moveToX,visibleSize.height/2));

				//m_PList->fParallaxMoveTo(ccp(visibleSize.width/2 - m_PList->fGetSizeX() - t->fGetRightX() + 200 ,visibleSize.height/2));
				m_PList->fParallaxMoveTo(ccp(-500 + visibleSize.width/2 + m_PList->fGetSizeX() - t->fGetLeftX() - 200 ,visibleSize.height/2));
				// Xoay mat sang trai
				m_Monkey->setDirection(MKLEFT);

			}else{
				CCLog("May se phai chet --> Nga ngua");
				m_Monkey->setStatus(MKFALL);
			}

            isTouchDown = false;
        }
        else if (initialTouchPos[0] - currentTouchPos[0] < - visibleSize.width * 0.05)
        {
            CCLOG("SWIPED RIGHT");
            
			if(m_RightTree < m_PList->fGetTrees()->count())
			{
				Tree *t = (Tree *) m_PList->fGetTrees()->objectAtIndex(m_RightTree);

				// Remove isChoose o cay hien tai
				Tree *t2 = (Tree *) m_PList->fGetTrees()->objectAtIndex(m_CurrentTree);
				t2->fSetIsChoose(false);

				t->fSetIsChoose(true);
				float moveToX = t->fGetLeftX();

				CCLog("Move to X = %f",moveToX);
				//m_PList->fParallaxMoveTo(ccp(-500 + visibleSize.width/2 + m_PList->fGetSizeX() - t->fGetLeftX() - 200 ,visibleSize.height/2));

				m_PList->fParallaxMoveTo(ccp(visibleSize.width/2 - m_PList->fGetSizeX() - t->fGetRightX() + 200 ,visibleSize.height/2));
				// Xoay mat sang phai
				m_Monkey->setDirection(MKRIGHT);
			}else{
				CCLog("May se phai chet --> Nga ngua");
				m_Monkey->setStatus(MKFALL);
			}
            isTouchDown = false;
        }
        else if (initialTouchPos[1] - currentTouchPos[1] > visibleSize.width * 0.05)
        {
            CCLOG("SWIPED DOWN");
            
            isTouchDown = false;
        }
        else if (initialTouchPos[1] - currentTouchPos[1] < - visibleSize.width * 0.05)
        {
            CCLOG("SWIPED UP");
            
            isTouchDown = false;
        }
    }
}

void HelloWorld::fAddMonkey()
{
	//mMonkey = new Monkey();
	//mMonkey->fSetPosition(300,200);
	//this->addChild(mMonkey,kZoderMonkey);
}

//------------------------------------>

void HelloWorld::ccTouchMoved(CCTouch* touch, CCEvent* event)
{
    CCPoint diff = touch->getDelta();
	xMoved_temp = touch->getLocation().x;

	//CCLog("Location X when moved = %f",touch->getLocation().x);
	//CCLog("Gia tri cua delta X = %f",diff.x);



	// Di chuyen den vi tri moi khi duoc swipe
 /*   CCNode* node = getChildByTag(1001);
    CCPoint currentPos = node->getPosition();
    node->setPosition( ccpAdd(currentPos, ccp(diff.x,currentPos.y)) );*/


	// Check swipe
	currentTouchPos[0] = touch->getLocation().x;
    currentTouchPos[1] = touch->getLocation().y;

}
bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    //mOriginalPos = mUnlocker->getPosition();
	CCLog("Touch began !!!! ");

	// Check swipe
	initialTouchPos[0] = touch->getLocation().x;
    initialTouchPos[1] = touch->getLocation().y;
    currentTouchPos[0] = touch->getLocation().x;
    currentTouchPos[1] = touch->getLocation().y;
    isTouchDown = true;


	CCLog("Current tree = %d",m_CurrentTree);

	// Khi cham vao man hinh thi con khi thay doi ben so voi cay
	/*
	Tree *currentTree = (Tree *) m_PList->fGetTrees()->objectAtIndex(m_CurrentTree);
	if(m_Monkey->getDirection() == MKLEFT)
	{
		m_Monkey->setDirection(MKRIGHT);
		m_PList->fParallaxMoveTo(ccp(visibleSize.width/2 - m_PList->fGetSizeX() - currentTree->fGetRightX() + 200 ,visibleSize.height/2));
	}else{
		m_Monkey->setDirection(MKLEFT);
		m_PList->fParallaxMoveTo(ccp(visibleSize.width/2 + m_PList->fGetSizeX() - currentTree->fGetLeftX() - 200,visibleSize.height/2));
	}
	*/
    return true;
}

void HelloWorld::ccTouchEnded(CCTouch* touch, CCEvent* event)
{
  
	xBegan_temp = 0;
	xMoved_temp = 0;



	isTouchDown = false;
}

void HelloWorld::onEnter() {
    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
    CCLayer::onEnter();
}

void HelloWorld::onExit() {
    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
    CCLayer::onExit();
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
	CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}
